package com.start.shop.common.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.start.shop.common.util.RedisService;
import com.start.shop.common.weixin.domain.WxUserInfo;
import com.start.shop.modules.repository.entity.User;


@WebFilter(urlPatterns = "/*")
public class Myfilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(Myfilter.class);

    @Autowired
    RedisService redisService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        logger.info("filter");
        //查询是否登录请求，登录请求透传
        if (requestURI.contains("login")||requestURI.contains("fail") || requestURI.contains("detail")&& request.getHeader("token")==null|| requestURI.contains("index")) {
            filterChain.doFilter(servletRequest, servletResponse);  //透传
        } else {
            //检查session
            String token = request.getHeader("token");
            String key = request.getHeader("key");

            if (token==null||token.length()==0) {
                //请求非法
                logger.info("没有token，直接返回");
                servletRequest.getRequestDispatcher("/fail/authFail").forward(servletRequest, servletResponse);
            } else {
            	 
                Object userObj = redisService.get(token.substring(0, 8));
                if (null == userObj) {
                    //请求非法
                    servletRequest.getRequestDispatcher("/fail/authFail").forward(servletRequest, servletResponse);
                    return;
                }
                logger.info(userObj.toString());
                User wxUser = JSON.parseObject(userObj.toString(), User.class);
                //校验token
                if (!wxUser.getToken().equals(token)) {
                	//请求非法
                    servletRequest.getRequestDispatcher("/fail/authFail").forward(servletRequest, servletResponse);
                    return;
				}
                logger.info("token验证成功");

                Map bodyMap = JSONObject.parseObject(getHttpServletRequestBody(request));
                bodyMap.put("user", wxUser);

                ModifyBodyHttpServletRequestWrapper wrapRequest = new ModifyBodyHttpServletRequestWrapper(request, JSON.toJSONString(bodyMap));

                filterChain.doFilter(wrapRequest, servletResponse);  //透传
            }
        }
    }

    @Override
    public void destroy() {
    }

    private String getHttpServletRequestBody(ServletRequest request) throws IOException {

        BufferedReader br = request.getReader();
        String str = "";
        String listString = "";
        while ((str = br.readLine()) != null) {
            listString += str;
        }

        return listString;
    }


}

